<!DOCTYPE html>
<html>
<head>
    <title>设置管理员</title>
    <#include "../../include/head-file.ftl">
</head>
<body>
<div id="form" v-cloak>
    <el-header class="ms-header ms-tr" height="50px">
        <el-button type="primary" icon="iconfont icon-baocun" size="mini" @click="save()" :loading="saveDisabled">保存</el-button>
        <el-button size="mini" icon="iconfont icon-fanhui" plain onclick="javascript:history.go(-1)">返回</el-button>
    </el-header>
    <el-main class="ms-container" style="overflow: hidden">
        <el-scrollbar class="ms-scrollbar" style="height: 100%;">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini">
                <el-row>
                    <el-col :span="12">
                        <el-form-item  label="账号" prop="managerName">
                            <el-input v-model="form.managerName"
                                      :disabled="false"
                                      :style="{width:  '100%'}"
                                      :clearable="true"
                                      maxlength="12"
                                      placeholder="请输入管理员账号">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item  label="昵称" prop="managerNickName">
                            <el-input v-model="form.managerNickName"
                                      :disabled="false"
                                      :style="{width:  '100%'}"
                                      maxlength="15"
                                      :clearable="true"
                                      placeholder="请输入管理员昵称">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="密码" v-if="switchIsShow" prop="managerPassword">
                            <el-input v-model="form.managerPassword"
                                      :disabled="false"
                                      maxlength="16"
                                      show-password
                                      :style="{width:  '100%'}"
                                      placeholder="请输入密码"
                                      :clearable="true">
                            </el-input>
                        </el-form-item>
                        <el-form-item v-else prop="managerPassword">
                            <span slot='label'>
                                密码<el-popover placement="top-start" title="提示" width="200" trigger="hover" content="注：编辑时，可不填">
                                        <i class="el-icon-question" slot="reference"></i>
                                    </el-popover>
                            </span>
                            <el-input v-model="form.managerPassword"
                                      :disabled="false"
                                      maxlength="16"
                                      show-password
                                      :style="{width:  '100%'}"
                                      :clearable="true">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item class="tree-table">
                    <span slot='label'>模块</span>
                    <el-table v-loading="loading" height="calc(100vh - 194px)" border :data="modelChildList" header-row-class-name='ms-table-head' row-class-name='ms-table-row'
                              row-key="id"
                              default-expand-all
                              :tree-props="{children: 'children'}">
                        <template slot="empty">
                            {{emptyText}}
                        </template>
                        <el-table-column label="模块标题" prop="modelTitle" width="300"></el-table-column>
                        <el-table-column label="功能权限">
                            <template slot-scope="scope" class="ms-row">
                                <div v-if= "scope.row.modelChildList.length>0">
                                    <label  class='ms-check'>
                                        <el-checkbox-group v-model="roleIds" @change="handleCheckedIdsChange">
                                            <el-checkbox v-for="model in scope.row.modelChildList" :label="model.id" :value='model.id' :key="model.id">{{model.modelTitle}}</el-checkbox>
                                        </el-checkbox-group>
                                    </label>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </el-main>
</div>
</body>
</html>
<script>
    var form = new Vue({
        el: '#form',
        data() {
            return {
                saveDisabled: false,
                //表单数据
                form: {
                    // 角色名称
                    managerName:'',//账号
                    managerNickName:'',//昵称
                    managerPassword:'',//密码
                    roleId:0,
                },
                managerWebsiteId:'',
                ids:'',
                roleIds:[], //选择的菜单
                modelChildList:[], //组菜单
                loading: true,
                emptyText:'',
                websiteId:'',
                switchIsShow: true,
                buttonList: [],
                rules:{
                    // 验证
                    managerName: [
                        {"required":true,"message":"请输入管理员帐号"},
                        {
                            validator: function (rule, value, callback) {
                                if (/^[a-zA-Z0-9_]+$/.exec(value) == null) {
                                    callback('帐号只能由英文字母，数字，下划线组成！')
                                }
                                callback();
                            },
                            trigger: ['change']
                        }],
                    managerNickName: [
                        {"required":true,"message":"请输入管理员昵称"},
                    ],
                    managerPassword: [
                        {
                            validator: function (rule, value, callback) {
                                if(value){
                                    if (/^[a-zA-Z0-9_]+$/.exec(value) == null) {
                                        callback('密码只能由英文字母，数字，下划线组成！')
                                    }
                                }
                                callback();
                            },
                            trigger: ['change']
                        }],
                },
            }
        },
        watch:{
        },
        computed:{
        },
        methods: {
            save() {
                var that = this;
                that.ids = '';
                var modelParentIds = '';

                for (var i = 0; i < that.roleIds.length; i++) {
                    //获取每个选中按钮权限的所有父级id
                    if (that.buttonList.filter(function (f) {
                        return f&&f['id'] == that.roleIds[i];
                    }).length > 0) {
                        modelParentIds = that.buttonList.filter(function (f) {
                            return f&&f['id'] == that.roleIds[i];
                        })[0].modelParentIds;

                        if (modelParentIds) {
                            that.roleIds = that.roleIds.concat(modelParentIds.split(",").map(Number));
                        }
                    }
                } //去重父级id


                that.roleIds = Array.from(new Set(that.roleIds));
                that.ids = that.roleIds.join(",");
                if (that.ids != "") { //是否选择了菜单
                    that.$refs.form.validate((valid) => {
                        if (valid) {
                            that.saveDisabled = true;
                            ms.http.post(ms.manager + "/website/manager/update.do?managerWebsiteId="+that.managerWebsiteId+"&modelIds="+ that.ids,that.form).then(function (data) {
                                if (data.result) {
                                    that.$notify({
                                        title: '成功',
                                        message: '保存成功',
                                        type: 'success'
                                    });
                                    that.saveDisabled = false;
                                    location.href = ms.manager + "/website/index.do";
                                } else {
                                    that.$notify({
                                        title: '失败',
                                        message: data.msg,
                                        type: 'warning'
                                    });
                                    that.saveDisabled = false;
                                }
                            });
                        } else {
                            return false;
                        }
                    })
                } else {
                    that.$notify({
                        title: '提示',
                        message: "请选择菜单",
                        type: 'warning'
                    });
                }
            },

            //获取当前角色管理
            get(id) {
                var that = this;
                ms.http.post(ms.manager + "/website/manager/" + id + "/edit.do").then(function (data) {
                    if (data.result) {
                        that.form = data.data;
                        that.modelList();
                        ms.http.get(ms.manager + "/basic/role/" + data.data.roleId + "/queryByRole.do").then(function (manager) {
                            if (manager.length > 0) {
                                for(item of manager){
                                    that.roleIds.push(item.id);
                                }
                            }
                        }).catch(function (err) {
                            console.log(err);
                        });
                        that.switchIsShow = false;
                    } else{
                        that.modelList();
                        that.rules.managerPassword.push({"required":true,"message":"请输入管理员密码"});
                    }
                }).catch(function (err) {
                    console.log(err);
                });
            },
            //获取所有菜单
            modelList: function(){
                var that = this;
                ms.http.post(ms.manager + "/mwebsite/model/query.do",{
                    "roleId": that.form.roleId
                }).then(function (data) {
                    if (data.data.total > 0) {
                        that.modelChildList = ms.util.treeData(data.data.rows.filter(function (f) {
                            return f['modelIsMenu'] == 1;
                        }), 'id', 'modelId', 'children'); //循环数组

                        for (var i = 0; i < data.data.rows.length; i++) {
                            if (data.data.rows[i].modelChildList.length > 0) {
                                for (var j = 0; j < data.data.rows[i].modelChildList.length; j++) {
                                    //判断是否选中
                                    if (data.data.rows[i].modelChildList[j].chick == 1) {
                                        that.roleIds.push(data.data.rows[i].modelChildList[j].id);
                                    }
                                }
                            }
                        }

                        //获取所有按钮菜单


                        var _iteratorNormalCompletion = true;
                        var _didIteratorError = false;
                        var _iteratorError = undefined;

                        try {
                            for (var _iterator = data.data.rows.filter(function (f) {
                                return f['modelIsMenu'] == 1;
                            })[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                                item = _step.value;
                                that.buttonList = that.buttonList.concat(item.modelChildList);
                            }
                        } catch (err) {
                            _didIteratorError = true;
                            _iteratorError = err;
                        } finally {
                            try {
                                if (!_iteratorNormalCompletion && _iterator.return != null) {
                                    _iterator.return();
                                }
                            } finally {
                                if (_didIteratorError) {
                                    throw _iteratorError;
                                }
                            }
                        }

                        that.emptyText = '';
                        that.loading = false;
                    } else {
                        that.loading = false;
                        that.emptyText = '暂无数据';
                        that.modelChildList = [];
                    }
                }).catch(function (err) {
                    console.log(err);
                });
            },
            //单元格事件
            handleCheckedIdsChange: function(value) {
                var that = this;
                that.roleIds = value;
            },
        },
        created() {
            this.websiteId = ms.util.getParameter("websiteId");
            this.get(this.websiteId);
            this.managerWebsiteId = this.websiteId;
        }
    });
</script>
<style>
    .tree-table>div:nth-of-type(1) {
        text-align: right;
    }
    .tree-table>div:nth-of-type(2) {
        margin-left: -10px;
        padding-right: 5px;
    }
    .el-form .ms-table-head {
        line-height: 0px;
    }
    .tree-table .cell.el-tooltip .ms-check {
        display: inline-block;
        margin-top: 3px;
        margin-right: 11px;
    }
</style>